import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {BaseComponent} from '../common/base.component';
import {FileUploader} from 'ng2-file-upload';
import {PathAddService} from './pathAdd.service';
import {AddPathInfo} from './pathAdd';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import 'rxjs/add/operator/toPromise';
import {UserService} from '../user/user.service';

declare var $: any;

@Component({
  selector: 'app-pathadd',
  templateUrl: './pathAdd.component.html'
})
export class PathAddComponent extends BaseComponent implements OnInit {
  uploader: FileUploader = new FileUploader({
    url: ParamConfig.HTTP_WEB_HOST_URL + 'rbFile/upload?type=0',
    method: 'POST',
    itemAlias: 'file'
  });
  private hostUrlAddPath = ParamConfig.HTTP_WEB_HOST_URL + 'path/savePath'; // URL to web api
  imgUrl: string;
  fileId: string;
  public token: string;
  addPathInfo: AddPathInfo[];
  curaddPathInfo: AddPathInfo;

  constructor(private http: Http, private router: Router, private pathAddService: PathAddService, private userService: UserService) {
    super();
  }

  ngOnInit() {
    this.token = this.userService.getToken();
    this.curaddPathInfo = {
      name: '',
      id: '',
      mapId: '',
      status: '',
      fileId: '',
      createTime: ''
    };
    this.getMapId();
  }

// 增加路径
  onAddPa() {
    this.addPathinfo(this.curaddPathInfo)
      .then(
        page => {
          if (page) {
            this.alert.info('新增成功');
            setTimeout(() => {
              this.router.navigate(['/buz/pathAdmin']);
            }, 1500);
          }
        }
      );
  }

  addPathinfo(addPathInfo: AddPathInfo): Promise<any> {
    const request = JSON.stringify({
      name: addPathInfo.name,
      status: addPathInfo.status,
      fileId: this.fileId,
      mapId: addPathInfo.mapId,
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlAddPath, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          } else {
            alert(body.msg);
          }
          if (body.status === 2) {
            alert(body.msg);
            this.router.navigate(['/login']);
          }
        }
      )
      .catch(this.handleError);
  }
  // 文件导入
  selectedFileOnChanged(event: any) {
    console.log(event.target.value);
    // 这里是文件选择完成后的操作处理
    this.uploader.queue[0].onSuccess = (response, status, headers) => {
      // 上传文件成功
      if (status === 200) {
        // 上传文件后获取服务器返回的数据
        const tempRes = JSON.parse(response);
        this.imgUrl = tempRes.systemFileTO.fileUrl;
        this.fileId = tempRes.systemFileTO.fileId;
      } else {
        // 上传文件后获取服务器返回的数据错误
      }
    };
    this.uploader.queue[0].upload(); // 开始上传
  }

// 查询mapId
  getMapId() {
    this.pathAddService.getMapIdInfo()
      .then(
        res => {
          if (res[0]) {
            this.addPathInfo = res[1].mapTO;
          }
        }
      );
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
